package cuishifeng.blog.mp3;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Mp3Get {

    public static void main(String[] args) throws Exception {

        // "https://m.9ku.com/play/1004523.htm"
        // https://m.9ku.com/play/875689.htm
        System.out.println("输入歌曲页面地址：");
        Scanner input = new Scanner(System.in);
        String url = input.next();

        if (url.contains("www")) {
            url = url.replace("www", "m");

        }
        System.out.println("url:" + url);
        Document document = Jsoup.connect(url.trim()).get();

        // System.out.println(document.outerHtml());

        org.jsoup.select.Elements ess = document.select("title");

        String title = ess.first().html();
        title = title.substring(0, title.length() - 18);

        System.out.println("title:" + title);

        org.jsoup.select.Elements es = document.select("script");
        String mp3Url = "";
        for (org.jsoup.nodes.Element e : es) {

            if (e.html().contains("mp3") && e.html().contains("meida")) {
                System.out.println(e.html());
                String[] ccs = e.html().split("mp3:");
                mp3Url = ccs[1].substring(1, ccs[1].length() - 3);
                System.out.println("mp3Url:" + mp3Url);
            }
        }
        if (StringUtils.isBlank(mp3Url)) {
            System.err.println("下载失败 无法找到 " + title + " mp3 地址！！！");
            return;
        }

        downLoadMp3FromUrl(mp3Url, "/Users/cuishifeng/Desktop/MP3/" + title + ".mp3");

    }

    static void downLoadMp3FromUrl(String downloadUrl, String filename) throws Exception {

        File file = FileUtils.getFile(filename);
        if (file != null && file.isFile()) {
            System.err.println("****** 已经下载过不要重复下载 *******");
            return;
        }

        URL download = new URL(downloadUrl);
        URLConnection con = download.openConnection();
        InputStream is = con.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        OutputStream os = new FileOutputStream(filename);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        System.out.println("====== 下载成功 ：" + filename + " =======");
        os.close();
        is.close();
    }

}
